package user.blog.post.comments;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import database.DataseConsult;

public class ManageComments {
	private List<Comment> comments;
	private String ownerLogin;
	
	public ManageComments(String ownerLogin) {
		comments = new ArrayList<Comment>();
		this.ownerLogin = ownerLogin;
	}
	
	public ManageComments(String ownerLogin, List<Comment> comments) {
		this.ownerLogin = ownerLogin;
		this.comments = comments;
	}
	
	public String addComment(String sessionId, String comment) throws Exception {
		Comment newComment = new Comment(comment, DataseConsult.getLoginByUID(sessionId), sessionId);
		comments.add(newComment);
		return newComment.getProperty(CommentFlags.CID);
	}
	
	public void save() throws IOException {
		Iterator<Comment> itComments = comments.iterator();
		final String PATH = "Database/" + ownerLogin +"/posts/";
		while(itComments.hasNext()) {
			Comment comment = itComments.next();
			
			FileOutputStream fos = new FileOutputStream(new File(PATH + comment.getProperty(CommentFlags.CID) + ".xml"));
			comment.getComment().storeToXML(fos, "This is a comment File");
			fos.close();
		}
	}
	
	public Integer getNumberOfComments() {
		return comments.size();
	}
	
	public String getComment(Integer index) {
		return comments.get(index).getProperty(CommentFlags.CID);
	}
	
	public String getCommentText(String idComment){
		Iterator<Comment> itComment = comments.iterator();
		while(itComment.hasNext()) {
			Comment tmpComment = itComment.next();
			if(tmpComment.getProperty(CommentFlags.CID).equals(idComment)) {
				return tmpComment.getProperty(CommentFlags.TEXT);
			}
		}
		
		return null;
	}
	
	public String getCommentAuthor(String idComment){
		Iterator<Comment> itComment = comments.iterator();
		while(itComment.hasNext()) {
			Comment tmpComment = itComment.next();
			if(tmpComment.getProperty(CommentFlags.CID).equals(idComment)) {
				return tmpComment.getProperty(CommentFlags.AUTHOR);
			}
		}
		
		return null;
	}
	
	public String getCommentByCID(String cid) {
		Iterator<Comment> itComments = comments.iterator();
		while(itComments.hasNext()) {
			Comment comment = itComments.next();
			if(cid.equals(comment.getProperty(CommentFlags.CID))) {
				return comment.getProperty(CommentFlags.TEXT);
			}
		}
		return null;
	}
	
	public List<Comment> getComments() {
		return comments;
	}
	
	public List<String> getCIDs() {
		List<String> cids = new LinkedList<String>();
		Iterator<Comment> itComments = comments.iterator();
		while(itComments.hasNext()) {
			cids.add(itComments.next().getProperty(CommentFlags.CID));
		}
		return cids;
	}
}